package org.example.template.services;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


@Component
public class TcpService {
    private final static Logger log = LoggerFactory.getLogger(Log.class);

    @Value("${tcp.port}")
    private int tcpport;


    public void tcpstate() {

        TcpThread tcpThread = new TcpThread(tcpport);
        tcpThread.start();
        log.info("准备打开TCP服务远程控制ESP8266,"+"端口为:"+tcpport+"...");





    }
}

class TcpThread extends Thread {
    private final static Logger log = LoggerFactory.getLogger(Log.class);
    //监听端口

    private int tcpport;

    public TcpThread( int tcpport) {
        this.tcpport = tcpport;
    }

    @Override
    public void run() {

        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            //建立服务器的Socket，并设定一个监听的端口PORT
            serverSocket = new ServerSocket(tcpport);
            //由于需要进行循环监听，因此获取消息的操作应放在一个while大循环中
            while (true) {
                try {
                    //建立跟客户端的连接
                    socket = serverSocket.accept();
                } catch (Exception e) {
                    log.error("建立与客户端的连接出现异常");
                    e.printStackTrace();
                }
                ESP8266TcpServerThread thread = new ESP8266TcpServerThread(socket);
                thread.start();
            }
        } catch (Exception e) {
            log.warn(tcpport+"端口被占用");

            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}


